import json
import time
from registrationapi import models
from django.http import JsonResponse
from . import algorithm
from django.db.models import Q

# 登录函数
def login(request):
    # 从request.body中加载json格式的数据
    data = json.loads(request.body)
    username = data['username']
    password = data['password']

    try:
        userinfo = models.UserInfo.objects.values()
        userinfo = userinfo.get(username=username)
        if userinfo['password'] == password:
            request.session['id'] = userinfo['id']
            request.session['username'] = userinfo['username']
            return JsonResponse({'code': 0, 'msg': '登录成功！', 'user': userinfo})
        else:
            print('failure: wrong password')
            return JsonResponse({'code': -2, 'msg': '密码错误！'})
    except models.UserInfo.DoesNotExist:
        print('failure: user does not exist')
        return JsonResponse({'code': -1, 'msg': '该用户名不存在！'})


# 注册函数
def register(request):
    # 从request.body中加载json格式的数据
    data = json.loads(request.body)
    username = data['username']
    password = data['password']
    phone = data['phone']
    email = data['email']

    if models.UserInfo.objects.filter(username=username):
        return JsonResponse({'code': -1, 'msg': '该用户名已存在！', 'username': username})

    models.UserInfo.objects.create(password=password, username=username, phone=phone, email=email)
    user_info = models.UserInfo.objects.values()
    user_info = user_info.get(username=username)
    return JsonResponse({'code': 0, 'msg': '注册成功！', 'user': user_info})


# 获取个人信息函数
def getinfo(request):
    # 从request.body中加载json格式的数据
    data = json.loads(request.body)
    username = data['username']

    userinfo = models.UserInfo.objects.values()
    userinfo = userinfo.get(username=username)

    return JsonResponse({'code': 0, 'msg': '获取成功！', 'userinfo': userinfo})


# 编辑个人信息函数
def editinfo(request):
    # 从request.body中加载json格式的数据
    data = json.loads(request.body)
    id = data['id']
    username = data['username']
    old_password = data['old_password']
    new_password = data['new_password']
    phone = data['phone']
    email = data['email']

    userinfo = models.UserInfo.objects.get(id=id)
    if userinfo.password == old_password:
        userinfo.username = username
        userinfo.password = new_password
        userinfo.phone = phone
        userinfo.email = email
        userinfo.save()

        new_userinfo = models.UserInfo.objects.values()
        new_userinfo = new_userinfo.get(id=id)
        return JsonResponse({'code': 0, 'msg': '修改成功！', 'userinfo': new_userinfo})
    else:
        print('failure: wrong password')
        return JsonResponse({'code': -2, 'msg': '原密码错误！'})


# 仅图片使用函数
def onlyimg(request):
    return JsonResponse({'code': 0, 'msg': 'Only Image！'})


# 上传图片函数
def uploadimg(request):
    # 从request.body中加载json格式的数据
    data = json.loads(request.body)
    p_name = data['p_name']
    p_sex = data['p_sex']
    p_age = data['p_age']
    doctor = data['doctor']
    stage = data['stage']
    date = str(data['date'][0:10])
    image_name = data['image_name']['file']['name']
    image_file = data['image_file']

    if models.ImageInfo.objects.filter(image_file=image_file):
        return JsonResponse({'code': -1, 'msg': '该图片已存在！'})

    models.ImageInfo.objects.create(
        p_name=p_name,
        p_sex=p_sex,
        p_age=p_age,
        doctor=doctor,
        stage=stage,
        date=date,
        image_name=image_name,
        image_file=image_file
    )
    models.ExtraImage.objects.create(old_image_base64=image_file)
    return JsonResponse({'code': 0, 'msg': '上传成功！'})


# 查询图片函数
def queryimg(request):
    # 从request.body中加载json格式的数据
    data = json.loads(request.body)

    img_list = models.ImageInfo.objects.all()
    img_list = list(img_list.values())
    total = len(img_list)
    if data['message'] == 'queryimg_six':
        page_number = data['pageNum']
        img_list = img_list[(page_number - 1) * 6:page_number * 6]
        return JsonResponse({'code': 0, 'msg': '查询成功！', 'total': total, 'img_list': img_list})
    elif data['message'] == 'queryimg_ten':
        return JsonResponse({'code': 0, 'msg': '查询成功！', 'total': total, 'img_list': img_list})
    else:
        return JsonResponse({'code': -1, 'msg': '传入参数错误！'})


# 删除图片函数
def deleteimg(request):
    # 从request.body中加载json格式的数据
    data = json.loads(request.body)
    id = data['image_id']

    delete_row = models.ImageInfo.objects.get(id=id)
    stage = delete_row.stage
    temporary = delete_row.image_file
    delete_row.delete()

    extra_row = models.ExtraImage.objects.get(id=id)
    extra_row.delete()

    if stage == '治疗前（参考图像）':
        registration_row = models.RegistrateImage.objects.filter(fixed_image=temporary)
    else:
        registration_row = models.RegistrateImage.objects.filter(moving_image=temporary)
    if registration_row != []:
        registration_row.delete()

    img_list = models.ImageInfo.objects.all()
    img_list = list(img_list.values())
    return JsonResponse({'code': 0, 'msg': '删除成功！', 'img_list': img_list})


# 判断日期函数
def is_valid_date(str):
  try:
    time.strptime(str, "%Y-%m-%d")
    return True
  except:
    return False


# 编辑图片函数
def editimg(request):
    # 从request.body中加载json格式的数据
    data = json.loads(request.body)
    id = data['image_id']
    p_name = data['p_name']
    p_sex = data['p_sex']
    p_age = data['p_age']
    doctor = data['doctor']
    stage = data['stage']
    date = data['date']
    image_name = data['image_name']

    edit_img = models.ImageInfo.objects.get(id=id)
    if p_sex not in ['男', '女']:
        return JsonResponse({'code': -1, 'msg': '性别只能是男或女！'})
    elif int(p_age) < 1:
        return JsonResponse({'code': -2, 'msg': '年龄不能小于1周岁！'})
    elif stage not in ['治疗前（参考图像）', '治疗后（浮动图像）']:
        return JsonResponse({'code': -3, 'msg': '阶段只能是【治疗前（参考图像）】或【治疗后（浮动图像）】！'})
    elif is_valid_date(date) == False:
        return JsonResponse({'code': -4, 'msg': '时间格式不正确！'})
    else:
        edit_img.p_name = p_name
        edit_img.p_sex = p_sex
        edit_img.p_age = p_age
        edit_img.doctor = doctor
        edit_img.stage = stage
        edit_img.date = date
        edit_img.image_name = image_name
        edit_img.save()

        img_list = models.ImageInfo.objects.all()
        img_list = list(img_list.values())
        return JsonResponse({'code': 0, 'msg': '编辑成功！', 'img_list': img_list})


# 请求配准的参考/浮动图像函数
def queryregistrationimg(request):
    # 从request.body中加载json格式的数据
    data = json.loads(request.body)
    image_type = data['type']

    if image_type == 'Fixed':
        fixed_image_list = models.ImageInfo.objects.filter(Q(stage='治疗前（参考图像）') & Q(is_ready=True) & Q(is_finish=False))
        fixed_image_list = list(fixed_image_list.values())
        return JsonResponse({'code': 0, 'msg': '查询成功！', 'image_list': fixed_image_list})
    elif image_type == 'Moving':
        moving_image_list = models.ImageInfo.objects.filter(Q(stage='治疗后（浮动图像）') & Q(is_ready=True) & Q(is_finish=False))
        moving_image_list = list(moving_image_list.values())
        return JsonResponse({'code': 0, 'msg': '查询成功！', 'image_list': moving_image_list})
    else:
        return JsonResponse({'code': -1, 'msg': '参数错误！'})


# 智能定点函数
def intelligentfixedpoint(request):
    # 从request.body中加载json格式的数据
    data = json.loads(request.body)
    stage = data['stage']
    long_image_file = data['long_image_file']
    short_image_file = data['short_image_file']

    after_fixed_point_image_file = algorithm.fixedPoint(short_image_file, stage)
    image_row = models.ExtraImage.objects.get(old_image_base64=long_image_file)
    image_row.point_image_base64 = after_fixed_point_image_file
    image_row.save()

    image_row = models.ExtraImage.objects.values()
    image_row = image_row.get(old_image_base64=long_image_file)
    return JsonResponse({'code': 0, 'msg': '定点成功！', 'extra_image': image_row})


# 智能绘制轮廓函数
def intelligentdrawoutlines(request):
    # 从request.body中加载json格式的数据
    data = json.loads(request.body)
    stage = data['stage']
    long_image_file = data['long_image_file']
    short_image_file = data['short_image_file']

    after_fixed_outlines_image_file, after_point_and_outlines_image_file = algorithm.fixedOutlines(short_image_file, stage)

    image_info = models.ImageInfo.objects.get(image_file=long_image_file)
    image_info.is_ready = True
    image_info.save()

    image_row = models.ExtraImage.objects.get(old_image_base64=long_image_file)
    image_row.outlines_image_base64 = after_fixed_outlines_image_file
    image_row.point_and_outlines_image_base64 = after_point_and_outlines_image_file
    image_row.save()

    image_row = models.ExtraImage.objects.values()
    image_row = image_row.get(old_image_base64=long_image_file)
    return JsonResponse({'code': 0, 'msg': '绘制成功！', 'extra_image': image_row})


# 配准函数
def registration(request):
    # 从request.body中加载json格式的数据
    data = json.loads(request.body)
    fixedImage = data['fixedImage']
    short_fixedImage = data['short_fixedImage']
    movingImage = data['movingImage']
    short_movingImage = data['short_movingImage']

    original_image, point_image, outlines_image, complete_image = algorithm.registrate(short_fixedImage, short_movingImage)
    models.RegistrateImage.objects.create(
        fixed_image=fixedImage,
        moving_image=movingImage,
        original_image=original_image,
        point_image=point_image,
        outlines_image=outlines_image,
        complete_image=complete_image
    )

    fixed_image_info = models.ImageInfo.objects.get(image_file=fixedImage)
    fixed_image_info.is_finish = True
    fixed_image_info.save()

    moving_image_info = models.ImageInfo.objects.get(image_file=movingImage)
    moving_image_info.is_finish = True
    moving_image_info.save()

    registration_image = models.RegistrateImage.objects.values()
    registration_image = registration_image.get(fixed_image=fixedImage)
    return JsonResponse({'code': 0, 'msg': '配准成功！', 'registration_image': registration_image})


# 查询生成的图像函数
def queryextraimage(request):
    # 从request.body中加载json格式的数据
    data = json.loads(request.body)
    image_file = data['image_file']

    extra_image = models.ExtraImage.objects.values()
    extra_image = extra_image.get(old_image_base64=image_file)

    return JsonResponse({'code': 0, 'msg': '查询成功！', 'extra_image': extra_image})


# 查询已配准好的图像函数
def queryhasregistrateimage(request):
    # 从request.body中加载json格式的数据
    data = json.loads(request.body)
    page_number = data['pageNum']

    has_registrate_image_list = models.RegistrateImage.objects.all()
    has_registrate_image_list = list(has_registrate_image_list.values())
    total = len(has_registrate_image_list)
    has_registrate_image_list = has_registrate_image_list[(page_number - 1) * 6:page_number * 6]
    return JsonResponse({'code': 0, 'msg': '查询成功！', 'total': total, 'has_registrate_image_list': has_registrate_image_list})


# 查询参考图像和浮动图像函数
def queryfixedandmoving(request):
    # 从request.body中加载json格式的数据
    data = json.loads(request.body)
    fixed_image = data['fixed_image']
    moving_image = data['moving_image']

    fixed_row = models.ImageInfo.objects.values()
    fixed_row = fixed_row.get(image_file=fixed_image)
    moving_row = models.ImageInfo.objects.values()
    moving_row = moving_row.get(image_file=moving_image)

    return JsonResponse({'code': 0, 'msg': '查询成功！', 'fixed_image': fixed_row, 'moving_image': moving_row})

